package com.imooc.web.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import com.fasterxml.jackson.annotation.JsonView;
import com.imooc.dto.User;
import com.imooc.dto.UserQueryCondition;
import com.imooc.security.core.properties.SecurityProperties;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 3.2.5 创建UserController
 * @author qilongfei
 *
 */
@RestController
//3.3.7 重构RequestMapping
@RequestMapping("/user")
/**
 * 6.7.13 测试访问 GET http://www.jeepupil.top/qqLogin/weixin?code=xxxxxx&state=xxxxxx
 * 用浏览器方式获取code后，app根据code获取token，首次要注册发生302跳转，跳到/social/singUp。
 * 【授权码模式】
 * HEADERS:
 * Authorization : Basic aW1vb2M6aW1vb2NzZWNyZXQ= [ Basic Username imooc Password imoocsecret ]
 * deviceId : 007 
 * 
 * 6.7.14 测试访问 GET http://www.jeepupil.top/social/user (socialSignUp)
 * HEADERS:
 * Authorization : Basic aW1vb2M6aW1vb2NzZWNyZXQ= [ Basic Username imooc Password imoocsecret ]
 * deviceId : 007 
 * signUp返回401，附带了微信的用户数据。app就知道要需要引导用户去注册或绑定
 * 
 * 6.7.15 测试访问 POST http://www.jeepupil.top/user/regist
 * HEADERS:
 * Authorization : Basic aW1vb2M6aW1vb2NzZWNyZXQ= [ Basic Username imooc Password imoocsecret ]
 * deviceId : 007 
 * BODY :
 * username[Text]: jojo
 * 当用户注册成功后，用6.7.5的方法持久化用户信息 imooc_userconnection表中会新增一条记录，同时redis缓存的用户信息也被清掉了
 */
public class UserController {
	
	@Autowired
	private ProviderSignInUtils providerSignInUtils;
	
	/*@Autowired
	private AppSignUpUtils appSignUpUtils;*/
	
	@Autowired
	private SecurityProperties securityProperties;
	
	/**
	 * 5.6.5 注册逻辑	
	 */
	@PostMapping("/regist")
	public void regist(User user, HttpServletRequest request){
		// 5.6.11 不管注册用户还是绑定用户，都会得到用户唯一标识
		String userId = user.getUsername();
		
		// 把userId传给springSocial，springSocial会把userId和获取到的openId一块插到imooc_userconnection表里去
		providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
		// TODO 对系统中用户表，增删该查。关联imooc_userconnection，处理注册或绑定业务*/		

		// 6.7.12 app演示使用app配置
		// appSignUpUtils.doPostSignUp(new ServletWebRequest(request), userId);
	}
	
	/**
	 * 4.6.2 获取当前用户认证信息
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws IllegalArgumentException 
	 * @throws SignatureException 
	 * @throws MalformedJwtException 
	 * @throws UnsupportedJwtException 
	 * @throws ExpiredJwtException 
	 */
	@GetMapping("/me")
	/*public Object getCurrentUser(){
		return SecurityContextHolder.getContext().getAuthentication();
	}*/
	/*public Object getCurrentUser(Authentication authentication){
		return authentication;
	}*/
	/*public Object getCurrentUser(@AuthenticationPrincipal UserDetails userDetails){
		return userDetails;
	}*/
	// 6.9.10 为了不反回null
	/*public Object getCurrentUser(Authentication user){
		return user;
	}*/
	// 6.9.19 改造代码，访问jwt中的自定义附加信息
	public Object getCurrentUser(Authentication user, HttpServletRequest request) throws Exception{
		String header = request.getHeader("Authorization");
		String token = StringUtils.substringAfter(header, "bearer ");
		
		// 签名用的是spring，验签的时候用io.jwtwebtoken，所以需要注意编码
		Claims claims = Jwts.parser().setSigningKey(securityProperties.getOauth2().getJwtSignKey().getBytes("UTF-8")).parseClaimsJws(token).getBody();
		
		String company = (String) claims.get("company");
		System.out.println("-->" + company);
		
		return user;
	}
	
	/**
	 * 3.2.7 查询用户列表controller
	 */
	// 3.3.7 重构RequestMapping
	// @RequestMapping(value="/user",method=RequestMethod.GET)
	@GetMapping
	// 3.3.5 controller添加视图
	@JsonView(User.UserSimpleView.class)
	// public List<User> query(@RequestParam(name="username", required=false, defaultValue="tom") String nickname){
	// 3.11.3 method自定义swagger描述
	@ApiOperation(value="用户查询服务")
	// 4.2.4 打断点 UserController-query  FilterSecurityInterceptor124 ExceptionTranslationFilter123 UsernamePasswordAuthenticationFilter75
	public List<User> query(UserQueryCondition condition, @PageableDefault(page = 2, size = 17, sort = "username,asc") Pageable pageable) {
		System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));
		System.out.println(pageable.getPageSize());
		System.out.println(pageable.getPageNumber());
		System.out.println(pageable.getSort());

		List<User> users = new ArrayList<>();
		users.add(new User());
		users.add(new User());
		users.add(new User());
		return users;
	}

	/**
	 * 3.3.2 查询单个用户controller
	 */
	// 3.3.7 重构RequestMapping
	// @RequestMapping(value="/user/{id:\\d+}", method = RequestMethod.GET)
	@GetMapping("/{id:\\d+}")
	// 3.3.5 controller添加视图
	@JsonView(User.UserDetailView.class)
	// 3.11.5 请求参数自定义swagger描述 @ApiParam
	public User getInfo(@ApiParam("用户ID") @PathVariable String id){
		/*System.out.println("进入getInfo服务");
		User user = new User();
		user.setUsername("tom");
		return user;*/
		// 3.6.1 服务异常处理
		// throw new RuntimeException("user not exists");

		// 3.6.5 抛出自定义异常
		// throw new UserNotExistException(id);
		
		// 3.7.3 恢复
		System.out.println("进入getInfo服务");
		User user = new User();
		user.setUsername("tom");
		return user;
	}
	
	/**
	 * 3.4.2 创建新用户controller
	 */
	// 3.4.4 Valid注解
	// 3.4.5 BindingResult注解
	@PostMapping
	public User create(@Valid @RequestBody User user,BindingResult errors){
		
		if(errors.hasErrors()){
			errors.getAllErrors().stream().forEach(error->System.out.println(error.getDefaultMessage()));
		}
		
		System.out.println(user.getId());
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		System.out.println(user.getBirthday());
		user.setId("1");
		return user;
	}

	/**
	 * 3.5.2 修改用户controller
	 * @param user
	 * @param errors
	 * @return
	 */
	@PutMapping("/{id:\\d+}")
	public User update(@Valid @RequestBody User user,BindingResult errors){
		
		if(errors.hasErrors()){
			errors.getAllErrors().stream().forEach(error->{
				/*FieldError fieldError = (FieldError)error;
				String message = fieldError.getField()+" "+error.getDefaultMessage();
				System.out.println(message);*/
				System.out.println(error.getDefaultMessage());
			});
		}
		
		System.out.println(user.getId());
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		System.out.println(user.getBirthday());
		user.setId("1");
		return user;
	}

	/**
	 * 3.5.9 删除用户controller
	 * @param id
	 */
	@DeleteMapping("/{id:\\d+}")
	public void delete(@PathVariable String id){
		System.out.println(id);
	}
}
